package ru.mipt.sport.gui.registry;

import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.util.Date;
import java.util.List;
import javax.persistence.EntityManager;
import javax.swing.*;
import ru.mipt.sport.model.entity.InstitutionEntity;
import ru.mipt.sport.model.entity.PersonEntity;
import ru.mipt.sport.model.interfaces.Institution;
import ru.mipt.sport.model.interfaces.Person;
import ru.mipt.sport.utils.DBUtils;

/**
 *
 * @author Danon
 */
public class AddPersonDialog extends javax.swing.JDialog {
    private final DBUtils db = DBUtils.getInstance();            
    
    /**
     * A return status code - returned if Cancel button has been pressed
     */
    public static final int RET_CANCEL = 0;
    /**
     * A return status code - returned if OK button has been pressed
     */
    public static final int RET_OK = 1;

    /**
     * Creates new form AddPersonDialog
     */
    public AddPersonDialog(java.awt.Frame parent, boolean modal, Person person) {
        super(parent, modal);
        initComponents();
        
        refreshInstitutions();

        // Close the dialog when Esc is pressed
        String cancelName = "cancel";
        InputMap inputMap = getRootPane().getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
        inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), cancelName);
        ActionMap actionMap = getRootPane().getActionMap();
        actionMap.put(cancelName, new AbstractAction() {

            @Override
            public void actionPerformed(ActionEvent e) {
                doClose(RET_CANCEL);
            }
        });
        
        if(person==null)
            person = new PersonEntity();
        this.person = person;
        if(this.person.getId()==null) {
            setTitle("New Person...");
        } else {
            setTitle("Edit Person...");
        }
        fillFromEntity();
    }

    /**
     * @return the return status of this dialog - one of RET_OK or RET_CANCEL
     */
    public int getReturnStatus() {
        return returnStatus;
    }
    
    public Person getPerson() {
        return person;
    }
    
    private void fillFromEntity() {
        firstNameTF.setText(person.getFirstName());
        lastNameTF.setText(person.getLastName());
        middleNameTF.setText(person.getMiddleName());
        if(person.getGender()!=null) {
            if(person.getGender())
                maleRadioButton.setSelected(true);
            else femaleRadioButton.setSelected(true);
        }
        if(person.getBirthDate()!=null)
            birthDateSpinner.setValue(person.getBirthDate());
        universityCB.setSelectedItem(person.getCurrentInstitution());
        facultyTF.setText(person.getCurrentFaculty());
        groupNumberTF.setText(person.getCurrentGroupNumber());
    }
    
    private void refreshInstitutions() {
        DefaultComboBoxModel<Institution> model = (DefaultComboBoxModel<Institution>)universityCB.getModel();
        Object o = model.getSelectedItem();
        model.removeAllElements();
        synchronized (db) {
            EntityManager em = DBUtils.getInstance().getEntityManager();
            List<Institution> elements = em.createQuery("select i from InstitutionEntity i order by i.name", Institution.class).getResultList();
            for(Institution i : elements)
                model.addElement(i);
        }
        model.setSelectedItem(o);
    }
    
    private void collectData() {
        person.setFirstName(firstNameTF.getText());
        person.setLastName(lastNameTF.getText());
        person.setMiddleName(middleNameTF.getText());
        person.setBirthDate((Date)birthDateSpinner.getValue());
        if(maleRadioButton.isSelected())
            person.setGender(true);
        else if(femaleRadioButton.isSelected())
            person.setGender(false);
        else person.setGender(null);
        person.setCurrentInstitution((InstitutionEntity)universityCB.getSelectedItem());
        person.setCurrentFaculty(facultyTF.getText());
        person.setCurrentGroupNumber(groupNumberTF.getText());
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        buttonGroup1 = new javax.swing.ButtonGroup();
        okButton = new javax.swing.JButton();
        cancelButton = new javax.swing.JButton();
        firstNameTF = new javax.swing.JTextField();
        lastNameTF = new javax.swing.JTextField();
        middleNameTF = new javax.swing.JTextField();
        maleRadioButton = new javax.swing.JRadioButton();
        femaleRadioButton = new javax.swing.JRadioButton();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        universityCB = new javax.swing.JComboBox();
        addUniversityButton = new javax.swing.JButton();
        jLabel6 = new javax.swing.JLabel();
        facultyTF = new javax.swing.JTextField();
        jLabel7 = new javax.swing.JLabel();
        groupNumberTF = new javax.swing.JTextField();
        jLabel8 = new javax.swing.JLabel();
        birthDateSpinner = new javax.swing.JSpinner();

        setTitle("Person...");
        setResizable(false);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosed(java.awt.event.WindowEvent evt) {
                formWindowClosed(evt);
            }
            public void windowClosing(java.awt.event.WindowEvent evt) {
                closeDialog(evt);
            }
        });

        okButton.setText("OK");
        okButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                okButtonActionPerformed(evt);
            }
        });

        cancelButton.setText("Cancel");
        cancelButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cancelButtonActionPerformed(evt);
            }
        });

        buttonGroup1.add(maleRadioButton);
        maleRadioButton.setText("Male");

        buttonGroup1.add(femaleRadioButton);
        femaleRadioButton.setText("Female");

        jLabel1.setLabelFor(firstNameTF);
        jLabel1.setText("First name:");

        jLabel2.setLabelFor(lastNameTF);
        jLabel2.setText("Last name:");

        jLabel3.setLabelFor(middleNameTF);
        jLabel3.setText("Middle name:");

        jLabel4.setLabelFor(maleRadioButton);
        jLabel4.setText("Gender:");

        jLabel5.setText("Birth date:");

        universityCB.setModel(new DefaultComboBoxModel<Institution>());

        addUniversityButton.setText("+");
        addUniversityButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                addUniversityButtonActionPerformed(evt);
            }
        });

        jLabel6.setLabelFor(universityCB);
        jLabel6.setText("University:");

        jLabel7.setLabelFor(facultyTF);
        jLabel7.setText("Faculty:");

        jLabel8.setLabelFor(groupNumberTF);
        jLabel8.setText("Group:");

        birthDateSpinner.setModel(new javax.swing.SpinnerDateModel(new java.util.Date(662677200000L), null, null, java.util.Calendar.DAY_OF_MONTH));
        birthDateSpinner.setEditor(new javax.swing.JSpinner.DateEditor(birthDateSpinner, "dd.MM.yyyy"));

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(0, 0, Short.MAX_VALUE)
                        .addComponent(okButton, javax.swing.GroupLayout.PREFERRED_SIZE, 67, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(cancelButton))
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel1)
                            .addComponent(jLabel2)
                            .addComponent(jLabel3)
                            .addComponent(jLabel4)
                            .addComponent(jLabel5)
                            .addComponent(jLabel6)
                            .addComponent(jLabel7)
                            .addComponent(jLabel8))
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(groupNumberTF, javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(facultyTF, javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(firstNameTF)
                            .addComponent(lastNameTF)
                            .addComponent(middleNameTF, javax.swing.GroupLayout.Alignment.TRAILING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(maleRadioButton)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(femaleRadioButton)
                                .addGap(0, 172, Short.MAX_VALUE))
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                                .addComponent(universityCB, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(addUniversityButton))
                            .addComponent(birthDateSpinner))))
                .addContainerGap())
        );

        layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {cancelButton, okButton});

        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(firstNameTF, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel1))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lastNameTF, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel2))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(middleNameTF, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel3))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(maleRadioButton)
                    .addComponent(femaleRadioButton)
                    .addComponent(jLabel4))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel5)
                    .addComponent(birthDateSpinner, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(universityCB, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(addUniversityButton)
                    .addComponent(jLabel6))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(facultyTF, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel7))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(groupNumberTF, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel8))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(cancelButton)
                    .addComponent(okButton))
                .addContainerGap())
        );

        getRootPane().setDefaultButton(okButton);

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void okButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_okButtonActionPerformed
        collectData();
        doClose(RET_OK);
    }//GEN-LAST:event_okButtonActionPerformed
    
    private void cancelButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelButtonActionPerformed
        doClose(RET_CANCEL);
    }//GEN-LAST:event_cancelButtonActionPerformed

    /**
     * Closes the dialog
     */
    private void closeDialog(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_closeDialog
        doClose(RET_CANCEL);
    }//GEN-LAST:event_closeDialog

    private void addUniversityButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addUniversityButtonActionPerformed
        AddInstitutionDialog dlg = new AddInstitutionDialog(null, true, null);
        dlg.setVisible(true);
        if (dlg.getReturnStatus() == AddInstitutionDialog.RET_OK) {
            Institution inst = dlg.getInstitution();
            synchronized (db) {
                try {
                    EntityManager em = db.getEntityManager(true);
                    em.persist(inst);
                    db.commit();
                } catch (Exception ex) {
                    db.rollback();
                }
            }
            refreshInstitutions();
        }
        
    }//GEN-LAST:event_addUniversityButtonActionPerformed

    private void formWindowClosed(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosed
        db.close();
    }//GEN-LAST:event_formWindowClosed
    
    private void doClose(int retStatus) {
        returnStatus = retStatus;
        setVisible(false);
        dispose();
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton addUniversityButton;
    private javax.swing.JSpinner birthDateSpinner;
    private javax.swing.ButtonGroup buttonGroup1;
    private javax.swing.JButton cancelButton;
    private javax.swing.JTextField facultyTF;
    private javax.swing.JRadioButton femaleRadioButton;
    private javax.swing.JTextField firstNameTF;
    private javax.swing.JTextField groupNumberTF;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JTextField lastNameTF;
    private javax.swing.JRadioButton maleRadioButton;
    private javax.swing.JTextField middleNameTF;
    private javax.swing.JButton okButton;
    private javax.swing.JComboBox universityCB;
    // End of variables declaration//GEN-END:variables
    private int returnStatus = RET_CANCEL;
    private Person person;
}
